import {createRouter, createWebHistory, useRouter} from "vue-router";
import {request} from "../api/baseFentch";
import {useStore} from "vuex";

const store = useStore()

const routes = [
    {
        path: '/',
        redirect: '/blog'
    },
    {
        path: '/blog',
        name: 'Blog',
        component: () => import('../views/blog/Blog.vue')
    },
    {
        path: '/blog/:id',
        name: 'BlogDetails',
        component: () => import('../views/blog/BlogDetails.vue')
    },
    /** 管理面板 */
    {
        path: "/admin/login",
        name: 'Login',
        component: () => import('../views/admin/Login.vue')
    },
    {
        path: '/admin',
        component: () => import('../views/admin/Dashboard.vue'),
        meta: {
            requireLogin: true
        }
    },
    {
        path: '/admin/blog',
        component: () => import('../views/admin/blog/BlogManager.vue'),
        meta: {
            requireLogin: true
        }
    },
    {
        path: '/admin/blog/edit',
        component: () => import('../views/admin/blog/EditBlog.vue'),
        meta: {
            requireLogin: true
        }
    },
    {
        path: '/admin/comment',
        component: () => import('../views/admin/comment/Comment.vue'),
        meta: {
            requireLogin: true
        }
    }
];

const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach((to, from) => {
    const rl = to.meta.requireLogin
    if (rl) {
        request("/auth").then(d => {
            if (d.code !== 0) {
                router.push(`/admin/login?refer=${to.path}`).then(() => "")
                return false;
            }
            window.localStorage.setItem('user', JSON.stringify(d.object))
        })
    }
    return true
})


export default router